package com.gzl.b2b.demo.service.impl;

import com.gzl.b2b.demo.dao.UserRepository;
import com.gzl.b2b.demo.entity.User;
import com.gzl.b2b.demo.service.UserService;
import org.apache.commons.collections4.IteratorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * demo service impl
 *
 * @version 1.0, 2019/4/12
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserRepository userRepository;

	@Override
	public boolean insert(User user) {
		boolean falg = false;

		try {
			userRepository.save(user);
			falg = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return falg;
	}

	@Override
	public List<User> saveAll(List<User> userIterable) {
		return IteratorUtils
				.toList(userRepository.saveAll(userIterable).iterator());
	}

	@Override
	public User findById(Long id) {
		Optional<User> userOptional = userRepository.findById(id);
		return userOptional.isPresent() ? userOptional.get() : null;
	}

	@Override
	public List<User> findAllById(List<Long> ids) {
		return IteratorUtils.toList(userRepository.findAllById(ids).iterator());
	}

	@Override
	public List<User> findAllById(User user) {

		return null;
	}

	@Override
	public List<User> findAll() {
		return IteratorUtils.toList(userRepository.findAll().iterator());
	}

	@Override
	public long count() {
		return userRepository.count();
	}

	@Override
	public boolean deleteById(Long id) {
		boolean falg = false;

		try {
			userRepository.deleteById(id);
			falg = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return falg;
	}

	@Override
	public void delete(User user) throws NullPointerException{
		if (user.getId() == null) {
			throw new NullPointerException("id is not null!");
		}
		userRepository.delete(user);
	}

	@Override
	public void deleteAll(List<User> userIterable) {
		userRepository.deleteAll(userIterable);
	}

	@Override
	public void deleteAll() {
		userRepository.deleteAll();
	}
}
